import { Component, OnInit } from '@angular/core';
import { NzFormatEmitEvent, NzMessageService, NzTreeNode } from 'ng-zorro-antd';
import { FetchService } from '../../../core/net/fetch.service';
import { takeUntil } from 'rxjs/operators';
import { BehaviorSubject, Subject } from 'rxjs';
import { MenuItemModel } from '../../../core/auth/auth.service';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';

@Component({
    selector: 'app-sf-prod-info',
    templateUrl: './sf-prod-info.component.html',
    styleUrls: ['./sf-prod-info.component.scss']
})
export class SfProdInfoComponent implements OnInit {
    dataSource;
    expandKeys;
    defaultKeys;
    searchValue = "";
    treeDataChange = new BehaviorSubject<MenuItemModel[]>([]);
    unsubscribe: Subject<void> = new Subject<void>();
    menuList: Array<MenuItemModel>;

    modalTitle: string = '';
    modalShow: boolean = false;
    nzBodyStyle: any = {
        padding: '16px 20px 0'
    };
    folderForm: FormGroup;
    activedNode: NzTreeNode;
    selectedItem: any = {};

    duty: string;
    deptId;
    tableData: Array<any> = [];
    pageNum = 1;
    pageSize = 10;
    total: number;
    loading = false;

    form: FormGroup;
    userModalTitle: string = '';
    userModalShow: boolean = false;
    constructor(private fetchService: FetchService,
                private message: NzMessageService,
                private fb: FormBuilder) {
        this.folderForm = this.fb.group({
            id: [''],
            name: ['', Validators.required],
            pid: ['', Validators.required],
            duty: ['']
        });
        this.form = this.fb.group({
            id: [null],
            deptId: [null],
            code: [null, Validators.required],
            name: [null, Validators.required],
            position: [null, Validators.required],
            duty: [null, Validators.required],
            skill: [null, Validators.required],
            phone: [null, Validators.required]
        });
    }

    ngOnInit(): void {
        this.treeDataChange.pipe(takeUntil(this.unsubscribe)).subscribe(data => {
            this.getTreeData(data);
            this.dataSource = data;
            if (data.length > 0) {
                this.expandKeys = [this.dataSource[0].key];
                this.defaultKeys = [this.dataSource[0].children[0].key];
                this.checkDetail(this.dataSource[0]);
            }

        });

        this.fetchMenuList();
    }
    getTreeData(data) {
        data.map(item => {
            item.title = item.name;
            item.key = item.id;
            if (item.children && item.children.length) {
                this.getTreeData(item.children);
            } else {
                item.isLeaf = true;
            }
        });
    }
    private fetchMenuList(force?: boolean): void {
        if (force || !this.menuList) {
            this.fetchService
                .post<any>("safeProduct/wrsSafeProductDept/list", {pageSize: 1000})
                .pipe(takeUntil(this.unsubscribe))
                .subscribe(res => {
                    res.list.unshift({id: 0, name: "全部单位", pid: null});
                    this.menuList = this.formatToCascadeData(res.list, 0);
                    this.treeDataChange.next(this.menuList);

                });
        }
    }
    private formatToCascadeData(data, rootId): any {
        const formatArr = data.map(item => {
            return {...item, ...{children: []}};
        });
        return this.listToTreeWithLevel(formatArr, null, 0, rootId);
    }

    private listToTreeWithLevel(list, parent, level, rootId?): Array<any> {
        const out = [];
        for (const node of list) {
            if (node.pid === parent) {
                node.level = level;
                const children = this.listToTreeWithLevel(list, node.id, level + 1, rootId);
                if (children.length) {
                    node.children = children;
                }
                out.push(node);
            }
        }
        return out;
    }
    // 查看
    checkDetail(e) {
        this.selectedItem = e.node ? e.node.origin : e;
        this.activedNode = e.node ? e.node : e;
        this.queryInfo();
    }
    editNode(item, e): void {
        console.log(item);
        this.modalTitle = '修改单位';
        this.modalShow = true;
        this.folderForm.patchValue(item);
    }

    addNode(item, e): void {
        this.modalTitle = '新增单位';
        this.modalShow = true;
        this.folderForm.reset();
        this.folderForm.patchValue({pid: item.id});
    }

    deleteNode(item, e): void {
        this.fetchService.get<any>(`safeProduct/wrsSafeProductDept/remove/${item.id}`)
            .subscribe(res => {
                this.fetchMenuList(true);
            });
    }

    queryInfo(reset: boolean = false): void {
        if (reset) {
            this.pageNum = 1;
        }
        this.loading = true;
        this.duty = this.selectedItem.duty;
        this.deptId = this.selectedItem.id;
        const params = {
            deptId: this.deptId,
            pageSize: this.pageSize,
            pageNum: this.pageNum
        };
        this.fetchService.post('safeProduct/wrsSafeProductUser/list', params).subscribe(res => {
            this.tableData = res['list'];
            this.total = res['total'];
            this.loading = false;
        });
    }

    onConfirm(): void {
        if (!this.folderForm.valid) {
            this.message.warning('信息填写有误');
            return;
        }
        const data = this.folderForm.value;
        if (data.id) {
            this.fetchService.post('safeProduct/wrsSafeProductDept/edit', data).subscribe(res => {
                this.modalShow = false;
                this.fetchMenuList(true);
            });
        } else {
            this.fetchService.post('safeProduct/wrsSafeProductDept/add', data).subscribe(res => {
                this.modalShow = false;
                this.fetchMenuList(true);
            });
        }
    }

    onCancel(): void {
        this.modalShow = false;
        this.folderForm.reset();
    }

    openEditModal(item?): void {
        this.userModalTitle = item ? `编辑` : '新增';
        this.form.reset(item || {});
        this.userModalShow = true;
    }

    onDelete(id) {
        this.fetchService.get(`safeProduct/wrsSafeProductUser/remove/${id}`).subscribe(resp => {
            this.message.info('删除成功');
            this.queryInfo();
        });
    }

    onUserCancel(): void {
        this.userModalShow = false;
        this.form.reset();
    }
    onUserConfirm(): void {
        if (!this.form.valid) {
            this.message.warning('信息填写有误');
            return;
        }
        const data = {
            ...this.form.value,
            deptId: this.selectedItem.id
        };
        const url = data.id ? 'safeProduct/wrsSafeProductUser/edit' : 'safeProduct/wrsSafeProductUser/add';
        this.fetchService.post(url, data).subscribe(res => {
            this.message.success('提交成功');
            this.userModalShow = false;
            this.queryInfo();
            this.form.reset();
        });
    }
}
